<template>
  <a-modal v-model:visible="vdata.visible" :maskClosable="false" width="41%" :title="'奖品绑定'">
    <a-form ref="formRef" layout="vertical" :wrapperCol="{ span: 22 }" :model="vdata.saveObject" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <a-form-item label="奖品类型" name="awardType">
            <a-radio-group v-model:value="vdata.saveObject['awardType']" @change="awardTypeChange">
              <a-radio v-if="vdata.awardType.includes(0)" :value="0">卡券</a-radio>
              <a-radio v-if="vdata.awardType.includes(1)" :value="1">实物</a-radio>
              <!-- <a-radio v-if="vdata.awardType.includes(2)" :value="2">虚拟券</a-radio> -->
              <a-radio v-if="vdata.awardType.includes(3)" :value="3">福分</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="(activityTemplateData.activityTemplateNo === 'ACTE001' || activityTemplateData.activityTemplateNo === 'ACTE008')" :span="12">
          <a-form-item label="奖品等级" name="awardLevel">
            <a-select v-model:value="vdata.saveObject['awardLevel']" placeholder="奖品等级">
              <a-select-option v-if="vdata.saveObject.awardType === 3" :value="0">安慰奖</a-select-option>
              <a-select-option :value="1" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 1)">一等奖</a-select-option>
              <a-select-option :value="2" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 2)">二等奖</a-select-option>
              <a-select-option :value="3" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 3)">三等奖</a-select-option>
              <a-select-option :value="4" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 4)">四等奖</a-select-option>
              <a-select-option :value="5" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 5)">五等奖</a-select-option>
              <a-select-option :value="6" :disabled="activityDetailInfo.activityAwardList.find(item => item.awardLevel === 6)">六等奖</a-select-option>
            </a-select>
            <span v-if="vdata.saveObject.awardLevel === 0" class="gz-tip-text">所有的空奖都改为安慰奖，若存在多个安慰奖，则每种安慰奖的中奖率为1/安慰奖总数量</span>
          </a-form-item>
        </a-col>
        <a-col v-if="(activityTemplateData.activityTemplateNo === 'ACTE001' || activityTemplateData.activityTemplateNo === 'ACTE008') && vdata.saveObject.awardLevel !== 0" :span="12">
          <a-form-item label="中奖概率" name="awardProbability">
            <a-input-number
              v-model:value="vdata.saveObject['awardProbability']"
              placeholder="中奖概率(0~100)"
              addon-after="%"
              :min="0.01"
              :max="100"
              :precision="2"
            />
          </a-form-item>
        </a-col>
        <a-col v-if="activityTemplateData.activityTemplateNo === 'ACTE024' && activityDetailInfo.activityShare.exchangeType !== 0" :span="12">
          <a-form-item label="奖品兑换所需积分" name="exchangeShareNum">
            <a-input-number v-model:value="vdata.saveObject['exchangeShareNum']" placeholder="请输入积分" :min="1" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <page-header-wrapper>
      <a-card class="table-card">
        <GzSearchForm :searchFunc="searchFunc" :resetFunc="() => { searchData = {} }" searchConditionNum="6">
          <a-form-item>
            <a-input v-model:value="searchData['batchNo']" placeholder="批次号" />
          </a-form-item>
        </GzSearchForm>
        <!-- 列表渲染 -->
        <gz-table
          ref="infoTableRef"
          :table-columns="tableColums"
          :init-data="false"
          :req-table-data-func="reqTableDataFunc"
          :search-data="searchData"
          :scrollX="600"
          :rowKey="vdata.rowKey"
          :row-selection="{ selectedRowKeys: vdata.selectedRowKeys, onSelect: onSelectChange, hideSelectAll: true }"
        >
          <template #topBtnSlot>
            <a-button type="primary" @click="handleAddAward"><plus-outlined />新建奖品</a-button>
          </template>
        </gz-table>
      </a-card>
    </page-header-wrapper>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-modal>
  <component :is="vdata.currentAwardDrawer" ref="currentAwardDrawerRef" :callbackFunc="searchFunc" />
</template>
<script setup lang="ts">
import { $getActivityList, API_URL_AWARD_GOODS_USABLE, API_URL_AWARD_COUPON_USABLE, API_URL_AWARD_VIRTUAL_USABLE, API_URL_AWARD_SCORE_USABLE } from '@/api/activityManage/activityCreate/index'
import { ref, reactive, defineExpose, nextTick, getCurrentInstance, inject } from 'vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

// 接收父组件的创建活动的详细参数
let activityDetailInfoInject: any = inject('activityDetailInfo')
let activityDetailInfo: any = activityDetailInfoInject.value
// 接收父组件的活动模板申请数据
let activityTemplateDataRef : any = inject('activityTemplateData')
let activityTemplateData : any = activityTemplateDataRef.value

const formRef = ref()
const infoTableRef = ref()
const currentAwardDrawerRef = ref()

const searchData = ref({})
const vdata: any = reactive({
  currentAwardDrawer: null,  // 当前奖品抽屉
  visible: false, // 弹窗显示状态 true显示 false隐藏

  rowKey: 'couponId',  // 表格行key
  awardMaxNum: 1,  // 奖品最大数量
  awardType: '0,1,2,3',  // 可以选择的奖品类型 0 卡券 1 实物 2 虚拟券 3 福分
  saveObject: {
    
  },

  selectedRowKeys: [],  // 选中要兑换的奖品
  rules: {
    awardLevel: [{ required: true, message: '奖品等级不能为空', trigger: ['blur','change'] }],
    awardProbability: [{ required: true, message: '中奖概率不能为空', trigger: ['blur','change'] }],
    exchangeShareNum: [{ required: true, message: '奖品兑换所需积分不能为空', trigger: ['blur','change'] }],
    awardType: [{ required: true, message: '奖品类型不能为空', trigger: 'blur' }],
  }
})

// 定义每种奖品类型的表头
const goodsColumns = [
  { key: 'batchNo', title: '批次号', dataIndex: 'batchNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'goodsName', title: '奖品名称', dataIndex: 'goodsName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'goodsNum', title: '奖品数量', dataIndex: 'goodsNum', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
]
const couponColumns = [
  { key: 'batchNo', title: '批次号', dataIndex: 'batchNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'couponName', title: '奖品名称', dataIndex: 'couponName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'couponNum', title: '奖品数量', dataIndex: 'couponNum', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
]
const virtualColumns = [
  { key: 'batchNo', title: '批次号', dataIndex: 'batchNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'goodsName', title: '奖品名称', dataIndex: 'goodsName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'goodsNum', title: '奖品数量', dataIndex: 'goodsNum', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
]
const scoreColumns = [
  { key: 'batchNo', title: '批次号', dataIndex: 'batchNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'scoreName', title: '奖品名称', dataIndex: 'scoreName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'scoreNum', title: '奖品数量', dataIndex: 'scoreNum', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
]

// 奖品列表请求地址 默认卡券
const awardUrl = ref(API_URL_AWARD_COUPON_USABLE)
// 奖品列表表头 默认卡券
const tableColums = ref(couponColumns)

function searchFunc() {
  infoTableRef.value.refTable(true)
}

// 1. 定义所有可能导入的组件路径的映射
const componentMap = {
  couponFullRandom: import('@/views/award/coupon/AddOrEditFullRandom.vue'),
  couponCopy: import('@/views/award/coupon/AddOrEditCopy.vue'),
  goods: import('@/views/award/goods/AddOrEdit.vue'),
  virtualCoupon: import('@/views/award/virtualCoupon/AddOrEdit.vue'),
  score: import('@/views/award/score/AddOrEdit.vue')
}

// 打开对应奖品抽屉
function handleAddAward(){
  let componentKey = ''
  let isFullRandom = false
  // 判断奖品类型 打开对应的抽屉
  if(vdata.saveObject['awardType'] === 0){  // 卡券
    if(convertAwardType(activityTemplateData.activityTemplateNo) !== 5){  // 满减随机减模板类型
      componentKey = 'couponFullRandom'
      isFullRandom = true
    }else{  // 微信代金券模板
      componentKey = 'couponCopy'
    }
  }else if(vdata.saveObject['awardType'] === 1){  // 实物
    componentKey = 'goods'
  }else if(vdata.saveObject['awardType'] === 2){  // 虚拟券
    componentKey = 'virtualCoupon'
  }else{  // 福分
    componentKey = 'score'
  }
  componentMap[componentKey].then(m => {
    vdata.currentAwardDrawer = m.default
    nextTick(() => {
      if(isFullRandom){
        currentAwardDrawerRef.value.show(false,convertAwardType(activityTemplateData.activityTemplateNo),false,false,1)
      }else{
        currentAwardDrawerRef.value.show(false,false,false,false,1)
      }
    })
  })
}
/**
 * 模板转换奖品类型
 * @param templateNo 模板编号
 */
function convertAwardType(templateNo){
  if(templateNo === 'ACTE020'){  // 满减随机减模板
    return 1
  }else if(templateNo === 'ACTE021'){  // 满减随机减模板
    return 2
  }else if(templateNo === 'ACTE015'){  // 微信代金券模板
    return 3
  }else if(templateNo === 'ACTE016'){  // 微信代金券模板
    return 4
  }else{  // 其他模板
    return 5
  }
}

// 请求table接口数据
function reqTableDataFunc(params: any) {
  if (vdata.saveObject.awardType === 0) {  // 卡券 需要过滤满减随机减卡券 只查询微信代金券 couponType = 5
    params.couponType = convertAwardType(activityTemplateData.activityTemplateNo)
  }
  return new Promise((resolve) => {
    $getActivityList(awardUrl.value, { ...params, state: 2, agentNo: activityDetailInfo.agentNo, payAuthId: activityDetailInfo.payAuthId }).then(res => {
      // 过滤掉已选择的奖品
      const awardSelected = activityDetailInfo.activityAwardList
      // 从结果中过滤掉已选择的奖品（根据奖品id和奖品类型判断是否是同一个奖品）
      const awardType = vdata.saveObject.awardType
      const awardId = awardType === 0 ? 'couponId' : (awardType === 1 ? 'goodsId' : (awardType === 2 ? 'virtualId' : 'scoreId'))
      const resFilter = res.filter(item => {
        return !awardSelected.some(award => award.awardId === item[awardId] && awardType === award.awardType)
      })
      resolve({ records: resFilter })
    })
  })
}

/**
 * 奖品类型切换
 */
function awardTypeChange(e) {
  // 切换请求地址 以及表头 刷新列表
  if (e.target.value === 0) { // 卡券
    awardUrl.value = API_URL_AWARD_COUPON_USABLE
    tableColums.value = couponColumns
    vdata.rowKey = 'couponId'
  } else if (e.target.value === 1) { // 实物
    awardUrl.value = API_URL_AWARD_GOODS_USABLE
    tableColums.value = goodsColumns
    vdata.rowKey = 'goodsId'
  } else if (e.target.value === 2) { // 虚拟券
    awardUrl.value = API_URL_AWARD_VIRTUAL_USABLE
    tableColums.value = virtualColumns
    vdata.rowKey = 'virtualId'
  } else {  // 福分
    awardUrl.value = API_URL_AWARD_SCORE_USABLE
    tableColums.value = scoreColumns
    vdata.rowKey = 'scoreId'
  }
  // 刷新列表
  nextTick(() => {
    infoTableRef.value.refTable(true)
  })
  vdata.selectedRowKeys = []
}

// 选择兑换的商品
function onSelectChange(record) {
  const awardType = vdata.saveObject.awardType
  const awardId = awardType === 0 ? 'couponId' : (awardType === 1 ? 'goodsId' : (awardType === 2 ? 'virtualId' : 'scoreId'))
  const awardName = awardType === 0 ? 'couponName' : (awardType === 1 ? 'goodsName' : (awardType === 2 ? 'goodsName' : 'scoreName'))
  const awardPrice = awardType === 0 ? 'couponPrice' : (awardType === 1 ? 'goodsPrice' : (awardType === 2 ? 'marketPrice' : 'scorePrice'))
  const awardNum = awardType === 0 ? 'couponNum' : (awardType === 1 ? 'goodsNum' : (awardType === 2 ? 'goodsNum' : 'scoreNum'))
  vdata.saveObject.awardName = record[awardName]
  vdata.saveObject.awardId = record[awardId]
  vdata.saveObject.awardPrice = record[awardPrice]
  vdata.saveObject.awardNum = record[awardNum]
  vdata.selectedRowKeys = [record[awardId]]
}

function handleOkFunc() {
  formRef.value.validate().then(() => {
    // 校验奖品是否选择
    if (vdata.selectedRowKeys.length === 0) {
      $infoBox.message.warn('请选择要绑定的奖品')
      return
    }
    // 判断绑定奖品是否达到最大数量
    // 判断当前备注的奖品是否达到最大值
    let currentAwards = activityDetailInfo.activityAwardList
    if(vdata.saveObject.remark){
      currentAwards = activityDetailInfo.activityAwardList.filter(award => award.remark === vdata.saveObject.remark)
    }
    if(currentAwards.length >= vdata.awardMaxNum && vdata.awardMaxNum !== -1){
      $infoBox.message.warn(`奖品数量达到最大限制${vdata.awardMaxNum}个，请先删除部分奖品后再添加`)
      return
    }
    const awardData = JSON.parse(JSON.stringify(vdata.saveObject))
    // 校验非福分奖品不能为安慰奖
    if(awardData.awardType !== 3 && awardData.awardLevel === 0){
      $infoBox.message.warn('非福分奖品不能为安慰奖，请更改奖品等级或选择福分奖品')
      return
    }
    // 校验安慰奖是否是无限制数量的奖品
    if(awardData.awardLevel === 0){  // 安慰奖 没有中奖概率
      // 删除中奖概率
      delete awardData.awardProbability
      if(awardData.awardNum !== 0){
        $infoBox.message.warn('请为安慰奖配置【无限制】数量的奖品')
        return
      }
    }else if(awardData.awardProbability){
      awardData.awardProbability = awardData.awardProbability * 100
    }
    activityDetailInfo.activityAwardList.push(awardData)
    $infoBox.message.success('奖品绑定成功')
    onClose()
  }).catch(() => { })
}

function show(remark, awardType, awardMaxNum) {
  // 如果存在remark 则需要在完成绑定时将remark作为奖品属性一并传递
  // 数据重置
  vdata.saveObject = {
    awardType: Number(awardType.split(',')[0]), // 最终选择的奖品类型 0 卡券 1 实物 2 虚拟券 3 福分
    remark: remark,  // 奖品备注 例如A、B、C
  }
  vdata.awardType = awardType
  vdata.awardMaxNum = awardMaxNum
  // 数据重置
  vdata.selectedRowKeys = []
  vdata.visible = true
  // 处理列表
  const e = { target: { value: vdata.saveObject.awardType } }
  awardTypeChange(e)
}

function onClose() {
  vdata.visible = false
}

defineExpose({
  show
})
</script>

<style lang="less" scoped>
:deep(.table-layer .table-search-item) {
  width: calc(100% / 3);
}
:deep(.ant-input-number) {
  width: 100%;
}
:deep(.ant-input-number-group-wrapper){
  width: 100%;
}
</style>